#include "node.h"

Node::Node(const std::vector<Token>& tokens) : tokens_(tokens), nodes_() {
	std::vector<Token>::const_iterator tokenBegin = tokens_.begin();
	std::vector<Token>::const_iterator tokenEnd;
	std::vector<Token> subTokens;
	if ((tokenEnd = findNextToken(";", tokenBegin)) != tokens_.end()) {
		nodeType_ = STATEMENT_LIST;
		while (1) {
			copy(tokenBegin, tokenEnd, subTokens.begin());
			nodes_.push_back(new Node(subTokens));
			if (tokenEnd == tokens_.end()) {
				break;
			}
			tokenBegin = tokenEnd + 1;
			tokenEnd = findNextToken(";", tokenBegin);
		}
	} else if ((tokenEnd = findNextToken(",", tokenBegin)) != tokens_.end()) {
		nodeType_ = EXPRESSION_LIST;
		while (1) {
			copy(tokenBegin, tokenEnd, subTokens.begin());
			nodes_.push_back(new Node(subTokens));
			if (tokenEnd == tokens_.end()) {
				break;
			}
			tokenBegin = tokenEnd + 1;
			tokenEnd = findNextToken(",", tokenBegin);
		}
	} else if ((tokenEnd = findNextToken("or", tokenBegin)) != tokens_.end()) {
		nodeType_ = OR_LIST;
		while (1) {
			copy(tokenBegin, tokenEnd, subTokens.begin());
			nodes_.push_back(new Node(subTokens));
			if (tokenEnd == tokens_.end()) {
				break;
			}
			tokenBegin = tokenEnd + 1;
			tokenEnd = findNextToken("or", tokenBegin);
		}
	} else if ((tokenEnd = findNextToken("and", tokenBegin)) != tokens_.end()) {
		nodeType_ = AND_LIST;
		while (1) {
			copy(tokenBegin, tokenEnd, subTokens.begin());
			nodes_.push_back(new Node(subTokens));
			if (tokenEnd == tokens_.end()) {
				break;
			}
			tokenBegin = tokenEnd + 1;
			tokenEnd = findNextToken("and", tokenBegin);
		}
	} else {
		nodeType_ = NONE;
	}
}

Node::~Node() {
	for (std::vector<Node*>::iterator i = nodes_.begin(); i < nodes_.end(); ++i) {
		delete *i;
	}
}

std::vector<Token>::const_iterator Node::findLastToken(const std::string& string) {
	std::vector<Token>::const_iterator last = tokens_.end();
	unsigned int bracketLevel = 0;
	for (std::vector<Token>::const_iterator i = tokens_.begin(); i < tokens_.end(); ++i) {
		if ((*i).second == "(") {
			++bracketLevel;
		} else if ((*i).second == ")") {
			--bracketLevel;
		} else if (bracketLevel == 0 && (*i).second == string) {
			last = i;
		}
	}
	return last;
}

std::vector<Token>::const_iterator Node::findNextToken(const std::string& string, std::vector<Token>::const_iterator begin) {
	unsigned int bracketLevel = 0;
	for (std::vector<Token>::const_iterator i = begin; i < tokens_.end(); ++i) {
		if ((*i).second == ")") {
			++bracketLevel;
		} else if ((*i).second == "(") {
			--bracketLevel;
		} else if (bracketLevel == 0 && (*i).second == string) {
			return i;
		}
	}
	return tokens_.end();
}

